package com.hhh.Controller;

import com.hhh.Pojo.Result;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class UpdatedController {

    @Value("${waimaiproject.path}")
    private String path;

    @GetMapping("/download")
    public Result Download(@RequestParam String name, HttpServletResponse response) throws IOException {
        log.info("下载图片");
//        打印当前目录
//        System.out.println(new File(".").getAbsolutePath());
        FileInputStream inputStream = new FileInputStream(path + name);
        OutputStream outputStream = response.getOutputStream();
        byte[] num = new byte[1024 * 1024 * 5];
        int len = 0;
        while (((len = inputStream.read(num)) != -1)) {
            outputStream.write(num, 0, len);
        }
        outputStream.close();
        inputStream.close();
        return Result.success(response);
    }

    //    上传文件
    //@PostMapping("/upload")
    public Result Upload(MultipartFile file) throws IOException {
        String name = file.getOriginalFilename();
        String imgname = UUID.randomUUID().toString() + name.substring(name.lastIndexOf("."));
        InputStream inputStream = file.getInputStream();
        OutputStream outputStream = new FileOutputStream(path + imgname);
        byte[] arr = new byte[1024 * 1024 * 5];
        int len = 0;
        while ((len = inputStream.read()) != -1) {
            outputStream.write(arr, 0, len);
        }
        outputStream.close();
        inputStream.close();
        return Result.success(imgname);
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(file.toString());

        //原始文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg

        //创建一个目录对象
        File dir = new File(path);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(path + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(fileName);
    }
}
